package com.jian.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jian.project.annotation.AuthCheck;
import com.jian.project.common.BaseResponse;
import com.jian.project.common.DeleteRequest;
import com.jian.project.common.ErrorCode;
import com.jian.project.common.ResultUtils;
import com.jian.project.constant.CommonConstant;
import com.jian.project.exception.BusinessException;
import com.jian.project.model.dto.tbuserinterface.TbUserInterfaceAddRequest;
import com.jian.project.model.dto.tbuserinterface.TbUserInterfaceInvokeRequest;
import com.jian.project.model.dto.tbuserinterface.TbUserInterfaceQueryRequest;
import com.jian.project.model.dto.tbuserinterface.TbUserInterfaceUpdateRequest;
import com.jian.project.model.entity.TbUserInterface;
import com.jian.project.model.entity.User;
import com.jian.project.model.vo.InterfaceLeftNumberVo;
import com.jian.project.model.vo.UserInterfaceVO;
import com.jian.project.service.TbUserInterfaceService;
import com.jian.project.service.UserService;
import com.jian.springbootdemosdk.JApiClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 帖子接口
 *
 * @author jian
 */
@RestController
@RequestMapping("/tbUserInterface")
@Slf4j
public class TbUserInterfaceController {

    @Resource
    private TbUserInterfaceService tbUserInterfaceService;

    @Resource
    private UserService userService;

    @Resource
    private JApiClient jApiClient;

    // region 增删改查

    /**
     * 创建
     *
     * @param tbUserInterfaceAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTbUserInterface(@RequestBody TbUserInterfaceAddRequest tbUserInterfaceAddRequest, HttpServletRequest request) {
        if (tbUserInterfaceAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TbUserInterface tbUserInterface = new TbUserInterface();
        BeanUtils.copyProperties(tbUserInterfaceAddRequest, tbUserInterface);
        // 校验
        tbUserInterfaceService.validTbUserInterface(tbUserInterface, true);
        User loginUser = userService.getLoginUser(request);
        tbUserInterface.setUserId(loginUser.getId());

        boolean result = tbUserInterfaceService.save(tbUserInterface);
        if (!result) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newTbUserInterfaceId = tbUserInterface.getId();
        return ResultUtils.success(newTbUserInterfaceId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTbUserInterface(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        TbUserInterface oldTbUserInterface = tbUserInterfaceService.getById(id);
        if (oldTbUserInterface == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldTbUserInterface.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = tbUserInterfaceService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新
     *
     * @param tbUserInterfaceUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTbUserInterface(@RequestBody TbUserInterfaceUpdateRequest tbUserInterfaceUpdateRequest,
                                                       HttpServletRequest request) {
        if (tbUserInterfaceUpdateRequest == null || tbUserInterfaceUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TbUserInterface tbUserInterface = new TbUserInterface();
        BeanUtils.copyProperties(tbUserInterfaceUpdateRequest, tbUserInterface);
        // 参数校验
        tbUserInterfaceService.validTbUserInterface(tbUserInterface, false);
        User user = userService.getLoginUser(request);
        long id = tbUserInterfaceUpdateRequest.getId();
        // 判断是否存在
        TbUserInterface oldTbUserInterface = tbUserInterfaceService.getById(id);
        if (oldTbUserInterface == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldTbUserInterface.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = tbUserInterfaceService.updateById(tbUserInterface);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<TbUserInterface> getTbUserInterfaceById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TbUserInterface tbUserInterface = tbUserInterfaceService.getById(id);
        return ResultUtils.success(tbUserInterface);
    }

    /**
     * 获取列表（仅管理员可使用）
     *
     * @param tbUserInterfaceQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    public BaseResponse<List<TbUserInterface>> listTbUserInterface(TbUserInterfaceQueryRequest tbUserInterfaceQueryRequest) {
        TbUserInterface tbUserInterfaceQuery = new TbUserInterface();
        if (tbUserInterfaceQueryRequest != null) {
            BeanUtils.copyProperties(tbUserInterfaceQueryRequest, tbUserInterfaceQuery);
        }
        QueryWrapper<TbUserInterface> queryWrapper = new QueryWrapper<>(tbUserInterfaceQuery);
        List<TbUserInterface> tbUserInterfaceList = tbUserInterfaceService.list(queryWrapper);
        return ResultUtils.success(tbUserInterfaceList);
    }

    /**
     * 分页获取列表
     *
     * @param tbUserInterfaceQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<TbUserInterface>> listTbUserInterfaceByPage(TbUserInterfaceQueryRequest tbUserInterfaceQueryRequest, HttpServletRequest request) {
        if (tbUserInterfaceQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TbUserInterface tbUserInterfaceQuery = new TbUserInterface();
        BeanUtils.copyProperties(tbUserInterfaceQueryRequest, tbUserInterfaceQuery);
        long current = tbUserInterfaceQueryRequest.getCurrent();
        long size = tbUserInterfaceQueryRequest.getPageSize();
        String sortField = tbUserInterfaceQueryRequest.getSortField();
        String sortOrder = tbUserInterfaceQueryRequest.getSortOrder();

        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        QueryWrapper<TbUserInterface> queryWrapper = new QueryWrapper<>(tbUserInterfaceQuery);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<TbUserInterface> tbUserInterfacePage = tbUserInterfaceService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(tbUserInterfacePage);
    }

    @PostMapping("/invoke_api")
    public BaseResponse<Boolean> invokeApi(@RequestBody TbUserInterfaceInvokeRequest request) {
        return ResultUtils.success(tbUserInterfaceService.invokeApi(request));
    }

    @GetMapping("/total")
    public BaseResponse<List<UserInterfaceVO>> getInvokeTotal(){
        return ResultUtils.success(tbUserInterfaceService.invokeTotal());
    }

    @PostMapping("/leftNumber")
    public BaseResponse<InterfaceLeftNumberVo> getLeftNumber(@RequestBody(required = false) TbUserInterfaceInvokeRequest tbUserInterfaceQueryRequest){
        if (tbUserInterfaceQueryRequest == null )
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        return ResultUtils.success(tbUserInterfaceService.getLeftNumber(tbUserInterfaceQueryRequest));
    }
}
